package controllers

import (
	"github.com/astaxie/beego"
	"log"
	"github.com/silenceper/wechat"
	"choujiang/conf"
	"encoding/base64"
	"choujiang/models"
	"time"
	"github.com/silenceper/wechat/oauth"
	"github.com/hundredlee/wechat_pusher/task"
	"github.com/hundredlee/wechat_pusher/enum"
	wxmodels "github.com/hundredlee/wechat_pusher/models"
	wxutils "github.com/hundredlee/wechat_pusher/utils"
)

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

func (c *MainController) Login() {
	wc := wechat.NewWechat(&conf.WX)
	//wc.GetServer(c.Ctx.Request, c.Ctx.ResponseWriter)
	oauth := wc.GetOauth()
	location, err := oauth.GetRedirectURL("http://cj.dhxsc.com/auth/code", "snsapi_userinfo", c.GetString("url"))
	if err != nil {
		log.Println(err)
	}
	c.Redirect(location, 302)
	c.StopRun()
}

func (c *MainController) Error() {
	c.TplName = "error.html"
}

func (c *MainController) GetCodeAndAuth() {
	ip := c.Ctx.Request.RemoteAddr
	if exist, _ := models.GetCache(ip); exist == "" {
		models.PutIntoCache(ip, "exist", time.Second*3)
	} else {
		c.StopRun()
		return
	}
	code := c.GetString("code")
	state := c.GetString("state")
	wc := wechat.NewWechat(&conf.WX)
	//wc.GetServer(c.Ctx.Request, c.Ctx.ResponseWriter)
	oauth := wc.GetOauth()
	log.Println("code & state is:", code, state)
	resToken, err := oauth.GetUserAccessToken(code)
	if err != nil {
		log.Println("err when get token", err)
	}
	userInfo, err := oauth.GetUserInfo(resToken.AccessToken, resToken.OpenID)
	if err != nil {
		log.Println("err when get userinfo", err)
		c.Redirect("/error", 302)
		return
	}
	user := models.Users{WxOpenId: userInfo.OpenID}
	if err := UpdateUser(&user, &userInfo); err != nil {
		log.Fatalln("update user wrong!", err)
		c.Redirect("/error", 302)
	}
	log.Println(userInfo)
	c.SetSession("openid", userInfo.OpenID)
	c.SetSession("type", 1)

	if state != "" {
		redirectUrl, _ := base64.StdEncoding.DecodeString(state)
		log.Println("redirect url", string(redirectUrl))
		c.Redirect(string(redirectUrl), 302)
	} else {
		c.Redirect("/userinfo", 302)
	}
}

func (c *MainController) Login_USER() {
	user := models.Users{Id: 1}
	models.UsersGetInfo(&user)
	log.Println(user.WxOpenId)
	c.SetSession("openid", user.WxOpenId)
	c.SetSession("type", 1)
	c.TplName = "devicelogin.html"
}

func (c *MainController) DeviceLogin() {
	if deviceid := c.GetSession("deviceid"); deviceid != nil {
		c.Redirect("/device/qrcode", 302)
	}
	Id, _ := c.GetInt("Id")
	Pass := c.GetString("Pass")
	if Id != 0 && models.CheckDevicePass(Id, Pass) {
		c.SetSession("type", 2)
		c.SetSession("deviceid", Id)
		c.Redirect("/device/qrcode", 302)
	}
	if c.GetString("Id") != "" {
		c.Data["wrongInfo"] = true
	}
	c.TplName = "devicelogin.html"
}

func (c *MainController) DeviceLogout() {
	c.DelSession("type")
	c.DelSession("deviceid")
	c.Redirect("/login/device", 302)
}

func (c *MainController) Message() {
	msg := c.GetString("msg")
	c.Data["msg"] = msg
	if c.GetSession("type").(int) == 2 {
		Message(&c.Controller, `/device/qrcode`, msg, "", false)
	} else {
		Message(&c.Controller, ``, msg, "", false)
	}
}

func (c *MainController) MessageUser() {
	msg := c.GetString("msg")
	c.Data["msg"] = msg
	if c.GetSession("type").(int) == 2 {
		Message(&c.Controller, `/device/qrcode`, msg, "", false)
	} else {
		Message(&c.Controller, ``, msg, "", false)
	}
}

func UpdateUser(user *models.Users, userInfo *oauth.UserInfo) error {
	if models.UsersExistByOpenid(user.WxOpenId) {
		if err := models.UsersGetInfoByWxOpenid(user); err != nil {
			return err
		}
		user.WxOpenId = userInfo.OpenID
		user.WxToken = userInfo.Nickname
		user.Sex = int(userInfo.Sex)
		user.Province = userInfo.Province
		user.City = userInfo.City
		user.Country = userInfo.Country
		user.HeadImgURL = userInfo.HeadImgURL
		user.Unionid = userInfo.Unionid
		if err := models.UsersUpdate(user); err != nil {
			return err
		}
	} else {
		user.WxOpenId = userInfo.OpenID
		user.WxToken = userInfo.Nickname
		user.Sex = int(userInfo.Sex)
		user.Province = userInfo.Province
		user.City = userInfo.City
		user.Country = userInfo.Country
		user.HeadImgURL = userInfo.HeadImgURL
		user.Unionid = userInfo.Unionid
		user.UserType = 0
		user.CreateTime = time.Now()
		user.UpdateTime = time.Now()
		if err := models.UsersInsert(user); err != nil {
			return err
		}
	}
	return nil
}

type Wx_Message struct {
	First    wxmodels.Raw `json:"first"`
	Keyword1 wxmodels.Raw `json:"keyword1"`
	Keyword2 wxmodels.Raw `json:"keyword2"`
	Keyword3 wxmodels.Raw `json:"keyword3"`
	Keyword4 wxmodels.Raw `json:"keyword4"`
	Keyword5 wxmodels.Raw `json:"keyword5"`
	Remark   wxmodels.Raw `json:"remark"`
}

func SendToWX(first, kehu, shijian, leixing, jifen, yue, remark, url string, openIds []string, templateId string) {
	log.Printf("wx message push %s,%s,%s,%s,%s,%s,%s,%s,%s\r\n", first, kehu, shijian, leixing, jifen, yue, remark, url, openIds[0])
	var tasks []task.Task
	AlarmColor := "#173177"

	//openIds := []string{"oM7kMwu0KozK7qEAc33KHDnq3L_M", "oM7kMwnl3LGc3Xs-Y3FxObrH6Q8Y", "oM7kMwoYenNeKJjPbn0qQpVDui5Y"}
	tasks = make([]task.Task, len(openIds))
	mess := wxmodels.Message{
		ToUser:     kehu,
		TemplateId: templateId,
		Url:        url,
		Data: Wx_Message{
			First:    wxmodels.Raw{first, AlarmColor},
			Keyword1: wxmodels.Raw{kehu, AlarmColor},
			Keyword2: wxmodels.Raw{shijian, AlarmColor},
			Keyword3: wxmodels.Raw{leixing, AlarmColor},
			Keyword4: wxmodels.Raw{jifen, AlarmColor},
			Keyword5: wxmodels.Raw{yue, AlarmColor},
			Remark:   wxmodels.Raw{remark, AlarmColor},
		},
	}

	for index, v := range openIds {
		task := task.TemplateTask{}
		mess.ToUser = v
		task.SetTask(mess)
		tasks[index] = &task
	}

	wxutils.NewPush(&wxutils.Push{
		Tasks:     tasks,
		TaskType:  enum.TASK_TYPE_TEMPLATE,
		Retries:   2,
		BufferNum: 10,
	}).RunRightNow("wxtask")
}


type Wx_Message_jifendaozhang struct {
	First    wxmodels.Raw `json:"first"`
	Keyword1 wxmodels.Raw `json:"keyword1"`
	Keyword2 wxmodels.Raw `json:"keyword2"`
	Keyword3 wxmodels.Raw `json:"keyword3"`
	Remark   wxmodels.Raw `json:"remark"`
}

func SendToWX_jifendaozhang(userOpenId,first, jifen, shijian, beizhu, remark, url string, openIds []string, templateId string) {
	log.Printf("wx message push %s,%s,%s,%s,%s,%s,%s,%s,%s\r\n", first, jifen, shijian, beizhu, remark, url, openIds[0])
	var tasks []task.Task
	AlarmColor := "#173177"

	//openIds := []string{"oM7kMwu0KozK7qEAc33KHDnq3L_M", "oM7kMwnl3LGc3Xs-Y3FxObrH6Q8Y", "oM7kMwoYenNeKJjPbn0qQpVDui5Y"}
	tasks = make([]task.Task, len(openIds))
	mess := wxmodels.Message{
		ToUser:     userOpenId,
		TemplateId: templateId,
		Url:        url,
		Data: Wx_Message_jifendaozhang{
			First:    wxmodels.Raw{first, AlarmColor},
			Keyword1: wxmodels.Raw{jifen, AlarmColor},
			Keyword2: wxmodels.Raw{shijian, AlarmColor},
			Keyword3: wxmodels.Raw{beizhu, AlarmColor},
			Remark:   wxmodels.Raw{remark, AlarmColor},
		},
	}

	for index, v := range openIds {
		task := task.TemplateTask{}
		mess.ToUser = v
		task.SetTask(mess)
		tasks[index] = &task
	}

	wxutils.NewPush(&wxutils.Push{
		Tasks:     tasks,
		TaskType:  enum.TASK_TYPE_TEMPLATE,
		Retries:   2,
		BufferNum: 10,
	}).RunRightNow("wxtask")
}
